﻿/*************************************************************************************

- CLR版本：        4.0.30319.42000
- 类 名 称：       SerialHelper
- 机器名称：       YTE
- 命名空间：       LD.Common
- 文 件 名：       SerialHelper
- 创建时间：       2022/7/25 14:17:51
- 作    者：       YTE
- 说   明：
- 修改时间：
- 修 改 人：
  *************************************************************************************/

using System;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace LD.Host
{
    public class SerialHelper : ICommunicate
    {
        private SerialPort serialPort;
        public event ConnectionStatusDelegate StatusEvent;
        private ManualResetEvent manualRest = new ManualResetEvent(false);
        private object obj = new object();
        public string Name { get; set; } = "";
        public SerialHelper(TB_HD param) : this(param.Name, param.Address, param.Port, param.Parity)
        {
            Name = param.Name;
        }
        public SerialHelper(string name, string portName, int baudRate, int parity)
            : this(name, portName, baudRate, parity > -1 ? (Parity)Enum.Parse(typeof(Parity), parity + "") : Parity.None, 8)
        {

        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="portName">端口</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="parity">校验位</param>
        /// <param name="stopBits">停止位</param>
        public SerialHelper(string name, string portName, int baudRate, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
        {
            Name = name;
            serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
            serialPort.DataReceived += SerialPort_DataReceived;
        }
        public byte[] ReceiveByte { get; set; }
        public bool IsOpen => serialPort.IsOpen;

        private Status status;
        public Status Status
        {
            get
            {
                return Status;
            }
            set
            {
                status = value;
                StatusEvent.Invoke(Name, value);
            }
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            ReceiveByte = new byte[serialPort.BytesToRead];
            serialPort.Read(ReceiveByte, 0, ReceiveByte.Length);
            Log4.Info("收到:" + Encoding.ASCII.GetString(ReceiveByte));
            manualRest.Set();
        }
        public void Send(byte[] bs)
        {
            lock (obj)
            {
                ReceiveByte = null;
                manualRest.Reset();
                if (!IsOpen)
                {
                    try
                    {
                        serialPort.Open();
                        Status = Status.成功;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Log4.Error(ex);
                    }
                }

                if (IsOpen)
                {
                    serialPort.DiscardInBuffer();
                    serialPort.DiscardOutBuffer();
                    Task.Delay(10).Wait();

                    serialPort.Write(bs, 0, bs.Length);
                    manualRest.WaitOne(3000);
                }
            }
        }

        public void Start()
        {
            try
            {
                serialPort.Open();
                Status = Status.成功;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Status = Status.失败;
                Log4.Error(ex);
            }
        }

        public void Stop()
        {
            try
            {
                serialPort.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
